package com.example.financeapi.controller;

import com.example.financeapi.config.constant.APIConstant;
import com.example.financeapi.config.annotation.PassToken;
import com.example.financeapi.config.wechat.ProjectUrlConfig;
import com.example.financeapi.config.wechat.mp.WxMpProperties;
import com.example.financeapi.utils.JsonUtils;
import com.example.financeapi.utils.RedisUtils;
import com.example.financeapi.entity.vo.ResultException;
import com.example.financeapi.entity.vo.ResultVOUtil;
import com.example.financeapi.entity.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;

@Slf4j
@RestController
@RequestMapping("/wechat")
public class WeChatController {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WxMpProperties wxMpProperties;

    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    /**
     * 访问这个时便会发起微信的网页授权
     * @param returnUrl
     * @return 发起授权是可携带的一个参数，我这里用的是下面将要用到的login()的地址，将获取到的openid传递过去
     * @throws WxErrorException
     */
    @GetMapping("authorize")
    public ResultVo authorize(String returnUrl) throws WxErrorException {
        //设置回调地址
        String redirectUrl="";
        String url = projectUrlConfig.getWechatMpAuthorize() + "/wechat/userInfo";
        if(StringUtils.isBlank(returnUrl)){
            redirectUrl=wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_BASE,null);
        }else{
            redirectUrl=wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_BASE,URLEncoder.encode(returnUrl));
        }
        log.info("【微信网页授权】获取code,result={}",redirectUrl);
        return ResultVOUtil.success(redirectUrl);
    }

    /**
     * 跳转获取微信openid信息
     * @param code
     * @param returnUrl
     * @return
     * @throws ResultException
     */
    @PassToken
    @GetMapping("/userInfo")
    public ResultVo userInfo(@RequestParam("code") String code,String returnUrl) throws ResultException {
        String openId ="";
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken=null;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            WxMpUser user = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            openId = wxMpOAuth2AccessToken.getOpenId();
            redisUtils.set(openId,openId, APIConstant.TOKEN_TIMES);
            log.info("【跳转获取微信openid信息】获取openid,result={},user={}",returnUrl+ "?openid=" + openId,user.toString());
            return ResultVOUtil.success("openid=" + openId);
        } catch (WxErrorException e) {
            log.error("【微信网页授权】e={}", e);
            return ResultVOUtil.success("openid=" + redisUtils.get("openId"));
            //throw new ResultException(e.getError().getErrorCode(),e.getError().getErrorMsg());
        }
    }

    /**
     * auth
     * @param code
     * @return
     */
    @PassToken
    @GetMapping("/auth")
    public ResultVo auth(@RequestParam("code") String code) {
        String getMyAppId =wxMpProperties.getConfigs().get(0).getAppId();
        String getMyAppSecret =wxMpProperties.getConfigs().get(0).getSecret();
        String url = String.format(APIConstant.SEND_OAUTH2_URL,getMyAppId,getMyAppSecret,code);
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        log.info("response={}", response);
        return ResultVOUtil.success(response);
    }

    /**
     * userInfo1
     * @param code
     */
    @PassToken
    @GetMapping("userInfo1")
    public void userInfo1(@RequestParam("code")String code){
        String openid="";
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = null;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            /**验证token*/
            boolean valid = wxMpService.oauth2validateAccessToken(wxMpOAuth2AccessToken);
            log.info("valid={}",valid);
            //获得用户基本信息
            WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            log.error("【微信网页授权】 getOpenId={},wxMpUser={}", wxMpUser.getOpenId(), JsonUtils.toJson(wxMpUser));
        }catch (WxErrorException e){
            log.error("【微信网页授权】{}",e);
        }
        if(wxMpOAuth2AccessToken!=null){
            openid=wxMpOAuth2AccessToken.getOpenId();
        }
        log.info("openid={}",openid);
    }

    /**
     * test
     * @return
     */
    @PassToken
    @GetMapping("test")
    public ResultVo test(){
        String result =redisUtils.get("openId");
        return ResultVOUtil.success(result);
    }

}
